#ifndef SYS_UPDATEAGENTS_H
#define SYS_UPDATEAGENTS_H

#include "opcodes.h"

int SYS_UpdateAgents()
{
    aid_t i,finished_count=0;
    Agent_Var* agent;

    for(i = 0; i < tavm_active_agents_count; i++)
    {
        agent = &tavm_agents_v[i];
        if(agent->state != AS_FINISHED)
        {
            if(agent->state == AS_READY)
            {
                 if(agent->procAgent != 0)
                {
                    struct Agent_Var* p_agent = &tavm_agents_v[agent->procAgent];
                    agent->state = AS_RUNNING;
                    CPU_ExecuteOpcode(p_agent);

                    while(p_agent->critical)
                    {
                        if(p_agent->state == AS_WAITING)
                        {
                            break;
                        }
                        CPU_ExecuteOpcode(p_agent);
                    }
                }
                else
                {
                    agent->state = AS_RUNNING;
                    CPU_ExecuteOpcode(agent);

                    while(agent->critical)
                    {
                        if(agent->state == AS_WAITING)
                        {
                            break;
                        }
                        CPU_ExecuteOpcode(agent);
                    }
                }
            }
            else if(agent->state == AS_WAITING && agent->procAgent && (i != tavm_agents_v[agent->procAgent].procAgent))
            {
                CPU_ExecuteOpcode(agent);
            }
            if(agent->state == AS_RUNNING) agent->state = AS_READY;
        }
        else
        {
            finished_count++;
        }

    }
    if(finished_count>=tavm_active_agents_count) return 1;

    return 0;

}

#endif

